<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<link rel=stylesheet href="{{=URL('static','css/custom.css')}}" />
		{{include 'web2py_ajax.html'}}
		<!-- This is the initial import of the google javascript classes, notice that the "visualization", "drawing" and "places" libraries are included.
		the visualiztion library is required to load maps engine layers into the map, 
		the places library is required for the address search,
		the drawing library allows users to draw on the map for the measuring tool.
		Below that we have the google jsapi library as well, this file contains all the classes required for the google pie charts and other things. -->
		<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=geometry,drawing,visualization,places&key={{=apiKey}}"></script>
		<script type="text/javascript" src="https://www.google.com/jsapi"></script>
		<script type="text/javascript">
			// these are all the variables that will store the javascript objects for this page
			// we put these outside of the initialize function so that they can be accessed and have thier
			// attributes changed from outside of the function.
			var map;
			var infoWindow;
			var marker;
			var addListener;
			var addMouseOver;
			var addMouseOut;
			var overlays = [];
			var drawingManager;
			{{for layer in mapData:}}var {{=layer[0]}};
			{{pass}}

			// the below line is required to load up the googls jsapi packages that we will want to use later inside of our initialize function.
			google.load('visualization', '1.0', {'packages':['corechart']});

			function initialize() {

				// this is the initialization of the map object into the 'map' variable
				var mapOptions = {
					center: new google.maps.LatLng(-31.9014641, 116.165723),
					zoom: 12,
					mapTypeId: google.maps.MapTypeId.TERRAIN, //ROADMAP, HYBRID, TERRAIN, SATELLITE 
					disableDefaultUI: true, //- disables all controls, add controll with the below
					mapTypeControl: true,
					streetViewControl: true,
					streetViewControlOptions: {
						position: google.maps.ControlPosition.TOP_RIGHT,
					},
				};
				map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

				// this is the initialization of the info window object into the infoWindow variable
				var infoWindowOptions = {
					content: "loading",
				};
				infoWindow = new google.maps.InfoWindow(infoWindowOptions);

				// this is the listener function to listen for clicks on a GME layer then display the
				// infowindow for the clicked feature. Instead of opening an info window, you can also set this listener
				// up to open up a panel if you like. For explanatory purposes, this function is setup to do both.
				// This is just a function that will be called by each map layer that is inside a given mapid.
				addListener = function (layer) {
					google.maps.event.addListener(layer, 'click', function(event) {

					// <----------- Right Hand Panel Code Start ----------->
						// this bit gives the details panel some flare and makes it look like
						// it is animated. You can adjust the timing using the numbers inside the
						// hide/show methods to slow down or speed up the animation.
						$('#detailsPanel').hide(500);

						// the detailsPanelContent div is where we will display our dynamic content.
						// we can use javascript here to display different content depending on the attribute
						// data of a feature.

						// this event.getDetails() object is specific to the "DynamicMapsEngineLayer" object which is instantiated 
						// later in the code. If you were using "MaosEngintLayer" instead, you would not need to wrap all the listener
						// logic inside the "getDetails" function. You can call event.infoWindowHtml directly from the listener instead.
						event.getDetails(function(event){

							// the 'event.infoWindowHtml' can be used to get the text string of the clicked feature's 
							// infoWindow data that is configured in Maps Engine. You can then use javascript to read it
							// and the display the relevant information into what ever you like.
							var dataString = event.infoWindowHtml;

							// the 'event.latLng' can be used to get the google latlng object of the clicked location. 

							// <----------- InfoWindow/baloon Code Start ----------->
								infoWindow.setContent(event.infoWindowHtml);
								infoWindow.setPosition(event.latLng);
								infoWindow.open(map);
							// <----------- InfoWindow/baloon Code Finished ----------->

							// "PIN" is a field name of the Cadastre layer in the localgov demo map.
							// so if the substring "PIN" is found in the "dataString" string, then the feature
							// that the user clicked on must be a feature from the Cadastre Layer.
							if (dataString.indexOf("PIN") != -1) {
								// now that we know what layer we are dealing with, we can now tell the browser what and how
								// we want to display the data.

								// we will be putting in two charts into the detailsPanelContent div. So first, we will
								// create some new divs inside detailsPanelContent div to place our charts into.
								document.getElementById('detailsPanelContent').innerHTML = "<div id='piechartdiv1'></div><div id='piechartdiv2'></div>";

								// below is the code to put in a pie chart into the right hand dsiplay panel. For this to work
								// you will have needed to include "google.load('visualization', '1.0', {'packages':['corechart']});" 
								// outside of the "initialize function", search for that line to see what I mean.

							// <-------------- Google Pie Chart Start --------------->
								// we'll need to parse the dataString to get the data we want out of it.
								// for this pie chart I will be getting the value for the "Area" field, this involves parsing the text inside
								// of the event.infoWindowHtml and getting out the info that I want from it. The below is just me parsing the string.
								var area = parseInt(dataString.substring(dataString.search("AREA:</b> ") + 10, dataString.length - 1).split("<br>")[0])

								var data = new google.visualization.DataTable();
								data.addColumn('string', 'Area');
								data.addColumn('number', 'value');
								data.addRows([
									['Property Area', area],
									// as you can see below, this is a completely fictional value that I have created by using the "random()" function
									// for demonstrational purposes. You would probably want an actual value here.
									['Area of Mundaring', (area * (Math.floor(Math.random() * 10) + 1)) - area],
								]);

								var chartOptions = {'title':'Dynamic Content 1 - Area Pie',
									'width':350,
									'height':350};

								var chart = new google.visualization.PieChart(document.getElementById('piechartdiv1'));
								chart.draw(data, chartOptions);
							// <-------------- Google Pie Chart Finished --------------->

							// <-------------- Google Pie Chart Start --------------->
								// this is the same except instead of a Pie chart, we have a bar chart, they are build the same way. Only differeance
								// is that instead of calling "google.visualization.PieChart" to instantiate the chart object, we call "google.visualization.BarChart".
								var data = new google.visualization.DataTable();
								data.addColumn('string', 'Area');
								data.addColumn('number', 'value');
								data.addRows([
									['Property Area', area],
									['Area of Mundaring', (area * (Math.floor(Math.random() * 10) + 1)) - area],
								]);

								var chartOptions = {'title':'Dynamic Content 2 - Area Bar',
									'width':350,
									'height':350};

								var chart = new google.visualization.BarChart(document.getElementById('piechartdiv2'));
								chart.draw(data, chartOptions);
							// <-------------- Google Pie Chart Finished --------------->
							}
							// "GarbageDay" is a field name of the Waste Management layer in the localgov demo map.
							else if (dataString.indexOf("GarbageDay") != -1) {
								document.getElementById('detailsPanelContent').innerHTML = "this must be the waste management layer";
							}
							else {
								document.getElementById('detailsPanelContent').innerHTML = event.infoWindowHtml;
							}
					// <----------- Right Hand Panel Code Finished ----------->
						});
						// show the right hand panel div once everything has loaded up.
						$('#detailsPanel').show(500);
					});

					google.maps.event.addListener(layer, 'mouseover', function(event) {
						var style = layer.getFeatureStyle(event.featureId);
						style.fillOpacity = 0.8;
					});

					google.maps.event.addListener(layer, 'mouseout', function(event) {
						var style = layer.getFeatureStyle(event.featureId).resetAll();
					});
				};

				// this is a web2py for loop, the HTML inside the 'for' and the 'pass'
				// tags is written to the DOM each time the loop iterates through mapData
				// this is where the mapsengine layers from the map is added to the map.
				{{for layer in mapData:}}
					{{=layer[0]}} = new google.maps.visualization.DynamicMapsEngineLayer({
						mapId: "{{=mapid}}",
						layerKey: "{{=layer[2]}}",
						map: null,
						clickable: "true",
						suppressInfoWindows: 'false',
					});
					addListener({{=layer[0]}});
				{{pass}}

				// This is the marker object being initialized, the marker is used for the address
				// search. The initial map setting for the marker is "null", the marker will not appear
				// until the user does an address search.
				var markerOptions = {
					position: new google.maps.LatLng(-31.9014641,116.165723),
					map: null,
				};
				marker = new google.maps.Marker(markerOptions);

				// This is the address search code, it listens for an "enter" button
				// keypress to chagne the zoom and center of the map. The HTML is in
				// the searchBox div.
				var input = (document.getElementById('searchBoxInput'));
				var searchBox = new google.maps.places.SearchBox(input);

				google.maps.event.addListener(searchBox, 'places_changed', function() {
					var places = searchBox.getPlaces();
					var bounds = new google.maps.LatLngBounds();

					bounds.extend(places[0].geometry.location);

					map.fitBounds(bounds);
					map.setZoom(19);

					// this is how a marker can be placed and repositioned.
					marker.setMap(map);
					marker.setAnimation(google.maps.Animation.DROP);
					marker.setPosition(places[0].geometry.location);
					marker.setTitle(places[0].formatted_address);
				});

				google.maps.event.addListener(map, 'bounds_changed', function() {
					var bounds = map.getBounds();
					searchBox.setBounds(bounds);
				});

				// this is just to hide the legend information and the details panel when the map first loads up
				$('.legend').hide();
				$('#detailsPanel').hide();
				$('#toolsInfoWindow').hide();


			// <---------------Drawing Manager Start --------------->
			// This is the code that handles the measureing tool, we use the google drawing manager object to create
			// the drawing mechanizms.
				drawingManager = new google.maps.drawing.DrawingManager({
					drawingControl: false,
					drawingControlOptions: {
						position: google.maps.ControlPosition.TOP_CENTER,
						drawingModes: [
							google.maps.drawing.OverlayType.POLYLINE,
							google.maps.drawing.OverlayType.POLYGON
						]
					},

				});

				drawingManager.setMap(map);

				// this is the listener to listen out for the completion of the drawing, when it is completed
				// the google geometry library is used to find the total length of the poly line drawing.
				google.maps.event.addListener(drawingManager, "overlaycomplete", function(event) {
					if (event.type == google.maps.drawing.OverlayType.POLYLINE){
						overlays.push(event.overlay);
						drawingManager.setDrawingMode(null);

						var distanceM = google.maps.geometry.spherical.computeLength(event.overlay.getPath());
						var distanceKM = Math.round((distanceM/1000) * 10) / 10;
						
						document.getElementById('toolsContent').innerHTML = "<span style='font-size: 200%; color: grey;font-weight:bold;'>DISTANCE: " + "<span style='color: rgba(200,0,0, 1);'>" + String(distanceKM) + "</span>" + " km</span>";
						$('#toolsInfoWindow').show();
					}

					else if (event.type == google.maps.drawing.OverlayType.POLYGON){
						overlays.push(event.overlay);
						drawingManager.setDrawingMode(null);

						var areaM = google.maps.geometry.spherical.computeArea(event.overlay.getPath());
						var areaKM = Math.round((areaM/1000) * 10) / 10;

						document.getElementById('toolsContent').innerHTML = "<span style='font-size: 200%; color: grey;font-weight:bold;'>AREA: " + "<span style='color: rgba(200,0,0, 1);'>" + String(areaKM) + "</span>" + " sqkm</span>";
						$('#toolsInfoWindow').show();
					}
				});
			// <---------------Drawing Manager Stop --------------->

			} // this is the end of the Initialize function.

			// this function will clear all the overylays inside the overlays array, this currently only 
			// includes the measuring tool's polylines.
			function clearMap() {
				while(overlays[0]){
					overlays.pop().setMap(null);
				};
			}

			// this is the function that runs when the user clicks on the measureing tool, the drawingManager
			// is already initialized on map load, this function will just enable the drawing mode to start 
			// when the button is pressed.
			function measure() {
				clearMap();
				drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYLINE);
			}

			function area() {
				clearMap();
				drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
			}

			// This is the function that checks the checkboxes in the layer selector list and
			// sets the layer to displayed or not displayed depending on the value of the layer selector
			// checkboxes.
			function updateOptions() {
				var form = document.options;
				{{for layer in mapData:}}
					if (form.{{=layer[0]}}Control.checked){
						{{=layer[0]}}.setMap(map);
					} else {
						{{=layer[0]}}.setMap(null);
					}
				{{pass}}
			}

		</script>
	</head>

	<body onload="initialize()">
		<div id="map-canvas"></div>

		<div id="minimizer">
			<input type="image" onclick="$('#layerSelector').toggle('fast');" src="{{=URL('static','images/minimize.png')}}" onmouseover="this.src='{{=URL('static','images/minimizedark.png')}}'" onmouseout="this.src='{{=URL('static','images/minimize.png')}}'" width="13"/>
		</div>

		<div id="layerSelector">

			<div id="searchBox">
				<input id="searchBoxInput" type="text" size="37" placeholder="Address Search">
			</div>

			<div class="tools">
				<input type="image" onclick="measure();" src="{{=URL('static','images/ruler.png')}}" onmouseover="this.src='{{=URL('static','images/eraser.png')}}'" onmouseout="this.src='{{=URL('static','images/ruler.png')}}'" width="15"/>
				<input type="image" onclick="area();" src="{{=URL('static','images/polygon.png')}}" onmouseover="this.src='{{=URL('static','images/eraser.png')}}'" onmouseout="this.src='{{=URL('static','images/polygon.png')}}'" width="15"/>
			</div>

			<br>
			<span class="heading">{{=mapName}}</span>
			<form name="options" action="javascript:updateOptions();">
				<table border="0">
					<!-- this for loop populates the layerselector/legend with layers. -->
					{{for layer in mapData:}}
							<tr>
								<td>
									{{=layer[1]}}
									<!-- there is currently no way to get the legend info of a layer from GME
									some logic will need to be put in here to display the correct legend images
									you can use web2py if/else statements to display the correct imagery as shown
									below:

									layer[0] is the layer's javascript freindly name
									layer[1] is the layer's formatted display name
									layer[2] is the layer's key so that it can be identified by the map

									Check how the "mapData" variable is built in the default.py file.
									-->
									<div class="legend" id="{{=layer[0]}}DropDown">
										{{if layer[0] == "WasteManagementMundaring":}}
											<span class="smallHeading">Bin Days</span>
											<table border="0">
												<tr>
													<td><img src="{{=URL('static','images/Wednesdays.png')}}"/></td>
													<td>Wednesdays</td>
												<tr>
												<tr>
													<td><img src="{{=URL('static','images/Thursdays.png')}}"/></td>
													<td>Thursdays</td>
												<tr>
												<tr>
													<td><img src="{{=URL('static','images/Fridays.png')}}"/></td>
													<td>Fridays</td>
												<tr>
											</table>
										{{elif layer[0] == "CadastreMundaring":}}
											<table border="0">
												<tr>
													<td><img src="{{=URL('static','images/Cadastre.png')}}"/></td>
													<td>Cadastre</td>
												<tr>
											</table>
										{{else:}}
											put your custom legend html here.
										{{pass}}
									</div>
								</td>
								<!-- the below onclick statement will call the 'updateOptions' function in the layout.html file
								which will set the 'map' as the location to display the layer data. After that it will use some
								jaquery to toggle show/hide on the legend div above -->
								<td valign="top"><input type="checkbox" onclick="updateOptions();$('#{{=layer[0]}}DropDown').toggle('fast');" name="{{=layer[0]}}Control" /></td>
							</tr>
					{{pass}}
				</table>
			</form>
		</div>

		<!-- This div is shown/hidden with the user clicks on layer features -->
		<div id="detailsPanel">
			<!-- This is a placeholder div to display dynamic javascript generated objects into 
			this is where your feature relative data could be displayed, if you wanted to put in anything 
			static, you can place it inside the #detailsPanel but outside of the detialsPanelContent div.-->
			<input type="image" onclick="$('#detailsPanel').hide();" src="{{=URL('static','images/close.png')}}" onmouseover="this.src='{{=URL('static','images/closedark.png')}}'" onmouseout="this.src='{{=URL('static','images/close.png')}}'" width="13"/>
			This is static html and will display above your dynamic stuff
			<div id="detailsPanelContent">
				This is where the dynamic content could be displayed, like piecharts
				and the like.
			</div>
			This is static html and will display below your dynamic stuff
		</div>

		<div id="toolsInfoWindow">
			<div id="toolsContent"></div>
			<span class="textButton" onclick="clearMap();$('#toolsInfoWindow').hide();">CLOSE</span>
		</div>

		<!-- This is the layout.html document which is just a template that will be added to the index.html view
		when web2py renders the webpage, the include statement lets web2py know where to put the index.html -->
		{{include}}
	</body>

	<footer>
		<!-- <p>this is the footer</p> -->
	</footer>
<html>